import { JSONFile } from "lowdb/node";
import { LowWithLodash } from "../model/DBWithLodash";

class DBFacory {
  #insMap = new Map<string, LowWithLodash<any>>();
  async #init<T>(path: string, schema: T) {
    const adapter = new JSONFile<T>(path);
    const db = new LowWithLodash(adapter, schema);
    // 将文件中的值同步至内存
    await db.read();
    return db;
  }

  async getIns<T>(path: string, schema: T) {
    if (this.#insMap.has(path)) return this.#insMap.get(path)!;
    const db = await this.#init(path, schema);
    this.#insMap.set(path, db);
    return db;
  }
}

export const dbFacory = new DBFacory();
